#include "ImagePlayerThread.h"
#include <QPixmap>
#include <QMetaObject>
#include <QDebug>

ImagePlayerThread::ImagePlayerThread(QLabel* displayLabel, QObject* parent)
    : QThread(parent), displayLabel(displayLabel), intervalMs(1000), isRunning(false)
{
}

void ImagePlayerThread::startPlayback(const QStringList& imagePaths, int intervalMs)
{
    this->imagePaths = imagePaths;
    this->intervalMs = intervalMs;
    if (!isRunning) {
        isRunning = true;
        start();
    }
}

void ImagePlayerThread::stopPlayback()
{
    isRunning = false;
    wait();
}

void ImagePlayerThread::run()
{
    int currentIndex = 0;
    while (isRunning && !imagePaths.isEmpty()) {
        QString imagePath = imagePaths.at(currentIndex);

        // 在主线程中更新UI
        QMetaObject::invokeMethod(this, [this, imagePath]() {
            QPixmap pixmap(imagePath);
            if (!pixmap.isNull()) {
                pixmap = pixmap.scaled(displayLabel->size(),
                                     Qt::KeepAspectRatio,
                                     Qt::SmoothTransformation);
                displayLabel->setPixmap(pixmap);
                emit imageChanged(imagePath);
            }
        });

        currentIndex = (currentIndex + 1) % imagePaths.size();
        msleep(intervalMs);
    }
}
